/*
 * Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"
#include "string.h"
#include "stdlib.h"
#include "hi_pwm.h"
/*Hello world*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_i2c.h"
#include "iot_gpio.h"
#include "iot_errno.h"
#include "oled_ssd1306.h"
#define LED_INTERVAL_TIME_US 300000
#define AHT20_BAUDRATE (400 * 1000)
#define AHT20_I2C_IDX 0
/*OLED控制*/
static void OledmentTask1(const char *arg)
{
    (void)arg;
    OledInit();
    OledFillScreen(0);
    IoTI2cInit(AHT20_I2C_IDX, AHT20_BAUDRATE);

    OledShowString(20, 3, "ABCD", 1); /* 屏幕第20列3行显示1行 */
}

static void OledDemo1(void)
{
    osThreadAttr_t attr;
    attr.name = "OledmentTask1";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 4096; /* 任务大小4096 */
    attr.priority = osPriorityNormal;

    if (osThreadNew(OledmentTask1, NULL, &attr) == NULL) {
        printf("[OledDemo] Falied to create OledmentTask!\n");
    }
}
 /*uart2串口通信*/
#include <hi_stdlib.h>
#include <hisignalling_protocol.h>
#include <hi_uart.h>
#include <uart11.h>
#include <iot_uart.h>
#include <hi_gpio.h>
#include <hi_io.h>
#include "iot_gpio_ex.h"
#include "ohos_init.h"
#include "cmsis_os2.h"

#define LED_TEST_GPIO 9 // for hispark_pegasus


static void Uart1GpioCOnfig1(void)
{
    IoSetFunc(HI_IO_NAME_GPIO_11, IOT_IO_FUNC_GPIO_11_UART2_TXD);
    IoSetFunc(HI_IO_NAME_GPIO_12, IOT_IO_FUNC_GPIO_12_UART2_RXD);
}


UartDefConfig uartDefConfig1 = {0};
//这个枚举在整个过程中没起到啥作用，可以忽略。
enum{
    WAIT,
	Open_Alarm,
    Close_Alarm,
    Kitchen_LED_Open,
    Kitchen_LED_Close,
    Living_LED_Open,
    Living_LED_Close,
    LED_Add,
    LED_Reduce
};

//检测串口指令
void Garbage_Uart_Cmd(char *str)
{
    char  *Str;
    unsigned char ID=255;
	
    Str=&str[1];//定位到指令的数字部分“G1”
    ID=atoi(Str);//将G后面的字符转换成十进制数据。
	
	if(strstr((const char *)str,"G")!=NULL)			//如果字符串str中包含有“G”
	{
		switch(ID)
		{
			case 1:	// 开灯
                printf("Open_Alarm\r\n");
                IoTGpioSetOutputVal(LED_TEST_GPIO, 0);
                TaskMsleep(2000);
				break;
			case 2:	// 关灯
                printf("Close_Alarm\r\n");
                IoTGpioSetOutputVal(LED_TEST_GPIO, 1);
                TaskMsleep(2000);
				break;
			case 3:	// 打开窗帘
                printf("Kitchen_LED_Open\r\n");
                OledDemo1();
                TaskMsleep(2000);
				break;
			case 4:	//  关闭窗帘
                printf("Kitchen_LED_Close\r\n");
                OledFillScreen(0);
                TaskMsleep(2000);
				break;
			default:
				printf("%s ERROR",str);
                //step =  WAIT;
				break;
		}
	}
    //memset(uart_buff,0,sizeof(uart_buff));//清空缓存数据，避免出错。
}


int SetUartRecvFlag1(UartRecvDef def)
{
    if (def == UART_RECV_TRUE) {
        uartDefConfig1.g_uartReceiveFlag = HI_TRUE;
    } else {
        uartDefConfig1.g_uartReceiveFlag = HI_FALSE;
    }
    
    return uartDefConfig1.g_uartReceiveFlag;
}

int GetUartConfig1(UartDefType type)
{
    int receive = 0;

    switch (type) {
        case UART_RECEIVE_FLAG:
            receive = uartDefConfig1.g_uartReceiveFlag;
            break;
        case UART_RECVIVE_LEN:
            receive = uartDefConfig1.g_uartLen;
            break;
        default:
            break;
    }
    return receive;
}

void ResetUartReceiveMsg1(void)
{
    (void)memset_s(uartDefConfig1.g_receiveUartBuff, sizeof(uartDefConfig1.g_receiveUartBuff),
        0x0, sizeof(uartDefConfig1.g_receiveUartBuff));
}

unsigned char *GetUartReceiveMsg1(void)
{
    return uartDefConfig1.g_receiveUartBuff;
}

static hi_void *UartDemoTask1(char *param)
{
    hi_u8 uartBuff1[UART_BUFF_SIZE] = {0};
    hi_unref_param(param);
        /*LED初始化*/
    IoTGpioInit(LED_TEST_GPIO);
    IoTGpioSetDir(LED_TEST_GPIO, IOT_GPIO_DIR_OUT);
    Uart1GpioCOnfig1();
    //OledDemo1();

    printf("Initialize uart demo successfully, please enter some datas via DEMO_UART_NUM port...\n");
    for (;;) {
        uartDefConfig1.g_uartLen = IoTUartRead(DEMO_UART_NUM, uartBuff1, UART_BUFF_SIZE);
        Garbage_Uart_Cmd((char *)uartBuff1);
        if ((uartBuff1[0] == 0x01)) {
            IoTGpioSetOutputVal(LED_TEST_GPIO, 0);
            TaskMsleep(2000);
        }
        if ((uartBuff1[0] == 0x02)) {
            IoTGpioSetOutputVal(LED_TEST_GPIO, 1);
            TaskMsleep(2000);
        }
        if ((uartBuff1[0] == 0x03)) {
            OledDemo1();
            IoTGpioSetOutputVal(LED_TEST_GPIO, 0);
            TaskMsleep(2000);
        }
        if ((uartBuff1[0] == 0x04)) {
            OledFillScreen(0);
            IoTGpioSetOutputVal(LED_TEST_GPIO, 1);
            TaskMsleep(2000);
        }
        //Garbage_Uart_Cmd((char *)uartBuff);//串口识别指令
        TaskMsleep(20); /* 20:sleep 20ms */
    }
    return HI_NULL;
}

/*
 * This demo simply shows how to read datas from UART2 port and then echo back.
 */
hi_void UartTransmit2(hi_void)
{
    hi_u32 ret1 = 0;

    IotUartAttribute uartAttr1 = {
        .baudRate = 9600, /* baudRate: 115200 */
        .dataBits = 8, /* dataBits: 8bits */
        .stopBits = 1, /* stop bit */
        .parity = 0,
    };
    /* Initialize uart driver */
    ret1 = IoTUartInit(DEMO_UART_NUM, &uartAttr1);
    //OledDemo1();
    if (ret1 != HI_ERR_SUCCESS) {
        printf("Failed to init uart! Err code = %d\n", ret1);
        return;
    }
    //OledDemo1();
    /* Create a task to handle uart communication */
    osThreadAttr_t attr1 = {0};
    attr1.stack_size = UART_DEMO_TASK_STAK_SIZE;
    attr1.priority = UART_DEMO_TASK_PRIORITY;
    attr1.name = (hi_char*)"uart demo1";
    if (osThreadNew((osThreadFunc_t)UartDemoTask1, NULL, &attr1) == NULL) {
        printf("Falied to create uart demo1 task!\n");
    }
}
SYS_RUN(UartTransmit2);